package com.whw.cbf_qimodazuoye.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.whw.cbf_qimodazuoye.R;
import com.whw.cbf_qimodazuoye.service.CheckOrderService;
import com.whw.cbf_qimodazuoye.utils.DaysUtil;
import com.whw.cbf_qimodazuoye.utils.FaSongQingQiu;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class OrderActivity extends AppCompatActivity {

    List<Integer> numberList = new LinkedList<>();
    List<String> RuZhuriqi = new LinkedList<>();
    List<String> LiKairiqi = new LinkedList<>();
    DateFormat format= DateFormat.getDateTimeInstance();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        Bundle bundle = this.getIntent().getExtras();
        final String hotelCoverpic = bundle.getString("hotelCoverpic");
        final String hotelIndexpic = bundle.getString("hotelIndexpic");
        final String hotelName = bundle.getString("hotelName");
        final String hotelIndex = bundle.getString("hotelIndex");
        final String hotelPrice = bundle.getString("hotelPrice");
        final String hotelId = bundle.getString("hotelId");
        final String hotelLabel = bundle.getString("hotelLabel");
        final String hotelNumber = bundle.getString("hotelNumber");
        final String userId = bundle.getString("userId");
        final String userIntegral = bundle.getString("userIntegral");
        final String userName = bundle.getString("userName");

        Button returnButton = findViewById(R.id.return1);
        returnButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("userId",userId);
                bundle.putString("userName",userName);
                bundle.putString("userIntegral",userIntegral);
                bundle.putString("hotelId",hotelId);
                bundle.putString("hotelPrice",hotelPrice);
                bundle.putString("hotelName",hotelName);
                bundle.putString("hotelIndex",hotelIndex);
                bundle.putString("hotelCoverpic",hotelCoverpic);
                bundle.putString("hotelIndexpic",hotelIndexpic);
                bundle.putString("hotelNumber",hotelNumber);
                bundle.putString("hotelLabel",hotelLabel);
                Intent intent=new Intent(OrderActivity.this,HotelActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });


        final EditText editTextcheckorderCheckInTime = findViewById(R.id.checkorderCheckInTime);
        final EditText editcheckorderCheckOutTime = findViewById(R.id.checkorderCheckOutTime);
        ImageView imageViewcheckorderCheckInTimeImage = findViewById(R.id.checkorderCheckInTimeImage);
        ImageView imageViewcheckorderCheckOutTimeImage = findViewById(R.id.checkorderCheckOutTimeImage);

        final EditText editTextorderActivityuserName = findViewById(R.id.orderActivityuserName);


        final EditText editTextorderActivityuserPhone = findViewById(R.id.orderActivityuserPhone);


        final EditText editTextorderActivityuserIdCard = findViewById(R.id.orderActivityuserIdCard);


        final EditText editTextorderActivityorderNumber = findViewById(R.id.orderActivityorderNumber);
       final String orderNumberEditText = editTextorderActivityorderNumber.getText().toString();

        final EditText editTextorderActivitycheckorderPrice = findViewById(R.id.orderActivitycheckorderPrice);


        imageViewcheckorderCheckInTimeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog1(OrderActivity.this,  4, editTextcheckorderCheckInTime, calendar);
            }
        });
        imageViewcheckorderCheckOutTimeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog2(OrderActivity.this,  4, editcheckorderCheckOutTime, calendar);
            }
        });

        editTextorderActivityorderNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date ruzhu = null;
                try {
                    ruzhu = simpleDateFormat.parse(RuZhuriqi.get(RuZhuriqi.size()-1));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Date likai = null;
                try {
                    likai = simpleDateFormat.parse(LiKairiqi.get(LiKairiqi.size()-1));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int tianshu = DaysUtil.queryNumberByStartAndEnd(ruzhu,likai)-1;
                Double price  =Double.parseDouble(hotelPrice);
                int number = Integer.parseInt(String.valueOf(s));
                Double zongjia = tianshu*price*number;
                editTextorderActivitycheckorderPrice.setText(zongjia.toString());
                numberList.add(number);
            }
        });

        Button bookingButoon = findViewById(R.id.orderBookingButton);
        bookingButoon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    final String userNameEditText = editTextorderActivityuserName.getText().toString();
                    final String userPhoneEditText = editTextorderActivityuserPhone.getText().toString();
                    final String userIdCardEditText = editTextorderActivityuserIdCard.getText().toString();
                    booking(userNameEditText,userPhoneEditText,userIdCardEditText,orderNumberEditText,hotelPrice,hotelId,userId,userName,userIntegral);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });




        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home,  R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        /**
                         * Intent intent=new Intent(MainActivity.this,MainActivity.class);
                         *                         startActivity(intent);
                         */

                        return true;

                    case R.id.navigation_notifications:
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("userId",userId);
                        bundle.putString("userName",userName);
                        bundle.putString("userIntegral",userIntegral);
                        Intent intent=new Intent(OrderActivity.this,MineActity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        return true;
                    }
                    case R.id.navigation_dashboard:{
                        Bundle bundle = new Bundle();
                        bundle.putString("userId",userId);
                        bundle.putString("userName",userName);
                        bundle.putString("userIntegral",userIntegral);
                        Intent intent=new Intent(OrderActivity.this,RecommendationActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        return true;
                    }
                }
                return false;
            }
        });
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showDatePickerDialog1(Activity activity, int themeResId, final TextView tv, Calendar calendar) {

        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {

            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
                int month123 =monthOfYear + 1;
                String day;
                day = year+"-"+month123+"-"+dayOfMonth;
                RuZhuriqi.add(day);
            }

        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showDatePickerDialog2(Activity activity, int themeResId, final TextView tv, Calendar calendar) {

        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {

            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
                int month123 =monthOfYear + 1;
                String day;
                day = year+"-"+month123+"-"+dayOfMonth;
                LiKairiqi.add(day);
            }

        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void booking(String userNameEditText, String userPhoneEditText, String userIdCardEditText, String orderNumberEditText, String hotelPrice,
                         String hotelId, final String userId, final String userName, final String userIntegral) throws ParseException
    {
        System.out.println("hotelId"+hotelId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date ruzhu = simpleDateFormat.parse(RuZhuriqi.get(RuZhuriqi.size()-1));
        Date likai = simpleDateFormat.parse(LiKairiqi.get(LiKairiqi.size()-1));
        int tianshu = DaysUtil.queryNumberByStartAndEnd(ruzhu,likai)-1;
        int price  =Integer.parseInt(hotelPrice);
        int number = numberList.get(numberList.size()-1);
        int zongjia = tianshu*price*number;




        Retrofit retrofit = FaSongQingQiu.createRetrofit();
        CheckOrderService checkOrderService = retrofit.create(CheckOrderService.class);
        Call<ResponseBody> call = checkOrderService.insertCheckOrder(
                RuZhuriqi.get(RuZhuriqi.size()-1),
                LiKairiqi.get(LiKairiqi.size()-1),
                number,
                zongjia,
                "ok",
                0,
                Integer.parseInt(hotelId),
                userId,
                userIdCardEditText,
                userNameEditText,
                userPhoneEditText);
        call.enqueue(new Callback<ResponseBody>() {
            //请求成功时回调
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //请求处理,输出结果
                try {
                    JSONObject jsonObject = (JSONObject) JSON.parse(response.body().string());
                    String msg =jsonObject.getString("msg");
                    String result = jsonObject.getString("result");

                    if (result.equals("true")){
                       Bundle bundle = new Bundle();
                       bundle.putString("userName",userName);
                       bundle.putString("userId",userId);
                       bundle.putString("userIntegral",String.valueOf(userIntegral));
                       Intent intent = new Intent(OrderActivity.this, MainActivity.class);
                       intent.putExtras(bundle);
                       startActivity(intent);
                       Toast.makeText(OrderActivity.this,"预定成功",Toast.LENGTH_LONG).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //JsonObject jsonObject = new JsonObject()
            }
            //请求失败时候的回调
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                System.out.println("连接失败");
            }
        });
    }
}
